<?php
header('Content-Type: application/json');

try {
    if (!isset($_FILES['cover']) || !isset($_POST['id'])) {
        throw new Exception('参数错误');
    }

    $id = $_POST['id'];
    $file = $_FILES['cover'];

    // 检查文件类型 
    $allowed = ['image/jpeg', 'image/jpg', 'image/png'];
    if (!in_array($file['type'], $allowed)) {
        throw new Exception('只允许上传 JPG 或 PNG 图片');
    }

    // 创建目录
    $uploadDir = __DIR__ . '/../../uploads/books/covers/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
        chmod($uploadDir, 0777);
    }

    // 直接使用上传的文件
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $id . '.' . $extension;
    $targetPath = $uploadDir . $filename;

    // 直接移动上传的文件
    if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
        throw new Exception('保存文件失败');
    }

    // 更新 books.json
    $booksFile = __DIR__ . '/../../data/books.json';
    $books = json_decode(file_get_contents($booksFile), true);
    
    foreach ($books['books'] as &$book) {
        if ($book['id'] == $id) {
            $book['cover'] = $filename;
            break;
        }
    }

    file_put_contents($booksFile, json_encode($books, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

    echo json_encode([
        'success' => true,
        'url' => "/admin/uploads/books/covers/{$filename}"
    ]);

} catch (Exception $e) {
    error_log('Upload Cover Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 